<template>
  <div>
    <el-card>
      <el-row>
        <span style="font-size: 23px;font-weight: bold">服务分类详情</span>
        <div class="custom-tabs"
             style="display: flex; justify-content: flex-end; margin-left: auto; margin-right: 20px;">
          <div class="custom-tab-btn"
               @click="$router.go(-1)">
            返&nbsp;回
          </div>
          <div class="custom-tab-btn"
               @click="page.reset()">
            重&nbsp;置
          </div>
          <div class="custom-tab-btn"
               :class="{ active: true }"
               @click="page.submit()">
            保&nbsp;存
          </div>
        </div>
      </el-row>
    </el-card>
    <div style="padding: 20px">
      <el-card class="centered-card">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
          <el-form-item label="服务名称：" prop="name">
            <el-input v-model="form.name"/>
          </el-form-item>
          <el-form-item label="服务介绍：" prop="introduction">
            <el-input type="textarea" v-model="form.introduction"/>
          </el-form-item>
          <el-form-item label="服务流程：" prop="process">
            <el-input type="textarea" v-model="form.process"/>
          </el-form-item>
          <el-form-item label="办结获得：" prop="obtained">
            <el-input type="textarea" v-model="form.obtained"/>
          </el-form-item>
          <el-form-item label="模板附件id：" prop="fileId">
            <el-input v-model="form.fileId"/>
          </el-form-item>
          <el-form-item label="父级服务：" prop="parentId">
            <el-cascader v-model="form.parentId"
                         :options="state.treeData"
                         :props="state.props1"
                         clearable
                         ref="cascaderAddr" placeholder="请选择上级项目" @change="getValue()" />
          </el-form-item>
          <el-form-item label="服务类型：" prop="type">
            <el-select v-model="form.type" placeholder="请选择服务类型">
              <el-option label="基础服务" value="0"/>
              <el-option label="拓展服务" value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="层   级：" prop="level">
            <el-input-number v-model="form.level"/>
          </el-form-item>
          <el-form-item label="服务描述：" prop="description">
            <el-input type="textarea" v-model="form.description"/>
          </el-form-item>
          <el-form-item label="是否发布：" prop="publishMark">
            <el-select v-model="form.publishMark" placeholder="请选择">
              <el-option label="是" value="1"/>
              <el-option label="否" value="0"/>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {getCurrentInstance, onBeforeMount, reactive, ref} from 'vue';
//引入树形组件的interface
//import {Tree} from "/@/components/ld/treeSelect.vue";
import {queryTree, querySvInfoEntity,saveSvInfo} from "/@/api/entService/serviceInfo";
import {useRoute, useRouter} from "vue-router";

const {proxy} = getCurrentInstance() as any;
const route = useRoute();
const cascaderAddr = ref();
const state = reactive({
  treeData: [],
  props1: {
    checkStrictly: true,
    label: "text",
    value: "id",
  },
});
// 定义表单数据
let form = reactive({
  id:"",
  name: '',
  introduction: '',
  process: '',
  obtained: '',
  fileId: '',
  parentId: '',
  type: '',
  level: 0,
  description: '',
  publishMark: '',
});

// 定义表单验证规则
const rules = {
  name: [{required: true, message: '请输入服务名称', trigger: 'blur'}],
  introduction: [{required: true, message: '请输入服务介绍', trigger: 'blur'}],
  process: [{required: true, message: '请输入服务流程', trigger: 'blur'}],
  obtained: [{required: true, message: '请输入办结获得', trigger: 'blur'}],
  type: [{required: true, message: '请选择服务类型', trigger: 'blur'}],
  level: [{required: true, message: '请输入层级', trigger: 'blur'}],
  description: [{required: true, message: '请输入服务描述', trigger: 'blur'}],
  publishMark: [{required: true, message: '请选择是否发布', trigger: 'change'}],
};

const formRef = ref(null);
// const convertTreeData = (originalNode: any): { value: string; label: string; children: { value: string; label: string; children: any[] }[] } => {
//   // 转换当前节点
//   const convertedNode = {
//     value: originalNode.id || '', // 使用 id 作为 value，如果 id 不存在则设为空字符串
//     label: originalNode.text || '', // 使用 text 作为 label，如果 text 不存在则设为空字符串
//     children: []
//   };
//
//   // 检查当前节点是否有子节点
//   if (originalNode.children && Array.isArray(originalNode.children)) {
//     // 遍历子节点，递归调用 convertTreeData 函数进行转换
//     convertedNode.children = originalNode.children.map((child: any) => convertTreeData(child));
//   }
//
//   return convertedNode;
// };
const getValue = () => {
  let changeId = proxy.$refs["cascaderAddr"].getCheckedNodes();
  form.parentId = changeId[0].value;
};

const page = {
  init: async () => {
    //初始化父级服务
    try {
        const tree = await queryTree();
        if (!tree.success) {
          proxy.$wigem.alert.error(tree.msg);
          return;
        }
        state.treeData = tree.data;
    } catch (error) {
      proxy.$wigem.alert.error("初始化父级服务失败！");
    }

    try {
      if (route.query.id) {
        const svInfo = await querySvInfoEntity(route.query.id);

        if (!svInfo.success) {
          proxy.$wigem.alert.error(svInfo.msg);
          return;
        }
        // 合并数据到 state.data
        for (const key in svInfo.data) {
          if (Object.prototype.hasOwnProperty.call(form, key)) {
            form[key] = svInfo.data[key];
          }
        }
      }
    } catch (error) {
      proxy.$wigem.alert.error("查询服务信息失败！");
    }
  },
  submit: async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid, fields) => {
      if (valid) {
        saveSvInfo(form).then(res => {
          if (res.success) {
            proxy.$wigem.alert.success(res.msg);
            proxy.$router.go(-1);
          }
        })
      } else {
        console.log('验证失败', fields);
      }
    });
  },
  reset: () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
  }
}


onBeforeMount(() => {
  page.init();
});
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
.custom-tabs {
  display: flex;
  gap: 10px;

  .custom-tab-btn {
    padding: 10px 28px;
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .custom-tab-btn.active {
    color: #ffffff;
    background-color: rgb(29, 133, 206);
  }

}

.centered-card {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh; /* 确保卡片至少占据整个视口高度 */
}

.centered-card .el-form {
  width: 100%;
  min-width: 800px;
  max-width: 1200px; /* 限制表单的最大宽度 */
}
</style>
